/* DirServ.java
 * Jeremiah Theurer
 * This file contains the code for the directory server for the VOIP project.
 */

import java.io.*;
import java.net.*;
import java.util.LinkedList;

public class DirServ
{	
	public static void main(String[] args) throws IOException//This code basically handles all the server side socket creation and giving the Connection Handler a socket to work with,
	{
		ServerSocket servSock = null;
		LinkedList<User> directory = new LinkedList<User>();
		try
		{
			System.out.println("Attempting to listen on 65535...");
			servSock = new ServerSocket(65535);
			System.out.println("Listening on 65535!");
		}
		catch(IOException e)
		{
			System.err.println("Could not listen on port: 65535");
			System.exit(1);
		}
	
		PrintThread t = new PrintThread(directory);
		new Thread(t).run();
		
		Socket clientSock = null;
		while(true)
		{
			try
			{
				System.out.println("Attempting to accept connections...");
				clientSock = servSock.accept();
				System.out.println("Connection Accepted!");
			}
			catch(IOException e)
			{
				System.err.println("Accept Failed.");
				System.exit(1);
			}
			
			Runnable connHandler = new ConnectionHandler(clientSock, directory);
			new Thread(connHandler).start();
		}
	}
	
	public static class PrintThread extends Thread {
		
		LinkedList<User> directory;
		
		public PrintThread(LinkedList<User> directory){
			this.directory = directory;
		}
		
		public void run(){
			// wait 10 seconds in between posts
			while (true){
				try{
					sleep(10000);
					if (directory.size() == 1){
						System.out.println("There is 1 current user:\n");
					} else {
						System.out.printf("There are %d current users:\n", directory.size());
					}
					for (int i = 0; i < directory.size(); i++){
						System.out.println(directory.get(i).userName);
					}
				}
				catch (Exception e){;}
			}
		}
	}
}
